#
# Module for calculating Bayesian probabilities of facts in the
# knowledge base
#
# P(A|B) = P(B|A)P(A) / P(B)
#
import math
import operator
from bbkb.KnowledgeBase import KnowledgeBase as kb

def calculate_probability(statement):
    # remove P() decoration
    statement = statement[2:-1]
    
    if '|' in statement:
        return _calculate_bayes(statement)
    else:
        return _calculate_joint_probability(statement)

def _calculate_bayes(statement):
    """Calculate Bayesian probability"""
    # TODO
    hypothesis, evidence_str = statement.split('|')
    evidence = evidence_str.split(',')
    print hypothesis, evidence
    
def _calculate_joint_probability(statement):
    """Calculate joint probability"""
    # TODO: need to do conditional
    probs = []
    questions = [s.strip() for s in statement.split(',')]
    for q in questions:
        table, value = q.split('=')
        value = value.replace("'",'')
        p = _lookup_table_to_probability(table)[value]
        probs.append(math.log(p))
    sum_p = sum(probs)
    return math.exp(sum_p)
    
    
def _lookup_table_to_probability(tablename):
    """Returns dict of value to probability"""
    table = kb.lookup_tables[tablename]
    total = sum(table[tid]['frequency'] for tid in table)
    probs = {}
    for tid in table:
        key = table[tid]['value']
        p = table[tid]['frequency'] / float(total)
        probs[key] = p
    return probs
    
def calculate_fact_frequency():
    """Calculates frequency of fact statements in knowledgebase"""
    freq = {}
    for stmt in kb.kb:
        fact = '~'.join([f.split(':')[0] for f in [facts for facts in stmt.split('~')]])
        count = freq.get(fact, 0)
        freq[fact] = count + 1
    return [(key, freq[key]) for key in sorted(freq, key=lambda key: freq[key], reverse=True)]